package com.coursehub.course.controller;

import com.coursehub.course.entity.Chapter;
import com.coursehub.course.service.ChapterService;
import com.coursehub.shared.dto.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.util.List;
import java.util.Optional;

/**
 * 章节管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/chapters")
@RequiredArgsConstructor
@Validated
public class ChapterController {
    
    private final ChapterService chapterService;
    
    /**
     * 创建章节
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Chapter>> createChapter(@Valid @RequestBody Chapter chapter) {
        log.info("创建章节请求: {}", chapter.getChapterName());
        Chapter createdChapter = chapterService.createChapter(chapter);
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(ApiResponse.success(createdChapter, "章节创建成功"));
    }
    
    /**
     * 根据ID获取章节
     */
    @GetMapping("/{chapterId}")
    public ResponseEntity<ApiResponse<Chapter>> getChapterById(
            @PathVariable @NotBlank(message = "章节ID不能为空") String chapterId) {
        Optional<Chapter> chapter = chapterService.getChapterById(chapterId);
        return chapter.map(c -> ResponseEntity.ok(ApiResponse.success(c)))
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 获取所有章节
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<Chapter>>> getAllChapters() {
        List<Chapter> chapters = chapterService.getAllChapters();
        return ResponseEntity.ok(ApiResponse.success(chapters));
    }
    
    /**
     * 根据课程ID获取章节列表
     */
    @GetMapping("/course/{courseId}")
    public ResponseEntity<ApiResponse<List<Chapter>>> getChaptersByCourseId(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId) {
        List<Chapter> chapters = chapterService.getChaptersByCourseId(courseId);
        return ResponseEntity.ok(ApiResponse.success(chapters));
    }
    
    /**
     * 根据课程ID获取章节ID列表
     */
    @GetMapping("/course/{courseId}/ids")
    public ResponseEntity<ApiResponse<List<String>>> getChapterIdsByCourseId(
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId) {
        List<String> chapterIds = chapterService.getChapterIdsByCourseId(courseId);
        return ResponseEntity.ok(ApiResponse.success(chapterIds));
    }
    
    /**
     * 更新章节信息
     */
    @PutMapping("/{chapterId}")
    public ResponseEntity<ApiResponse<Chapter>> updateChapter(
            @PathVariable @NotBlank(message = "章节ID不能为空") String chapterId,
            @Valid @RequestBody Chapter chapter) {
        log.info("更新章节请求: {}", chapterId);
        Chapter updatedChapter = chapterService.updateChapter(chapterId, chapter);
        return ResponseEntity.ok(ApiResponse.success(updatedChapter, "章节更新成功"));
    }
    
    /**
     * 删除章节
     */
    @DeleteMapping("/{chapterId}")
    public ResponseEntity<ApiResponse<Void>> deleteChapter(
            @PathVariable @NotBlank(message = "章节ID不能为空") String chapterId) {
        log.info("删除章节请求: {}", chapterId);
        chapterService.deleteChapter(chapterId);
        return ResponseEntity.ok(ApiResponse.success("章节删除成功"));
    }
    
    /**
     * 根据章节名称搜索章节
     */
    @GetMapping("/search")
    public ResponseEntity<ApiResponse<List<Chapter>>> searchChapters(
            @RequestParam(required = false) String chapterName) {
        List<Chapter> chapters;
        
        if (chapterName != null) {
            chapters = chapterService.searchChaptersByName(chapterName);
        } else {
            chapters = chapterService.getAllChapters();
        }
        
        return ResponseEntity.ok(ApiResponse.success(chapters));
    }
    
    /**
     * 验证章节是否存在
     */
    @GetMapping("/{chapterId}/validate")
    public ResponseEntity<ApiResponse<Boolean>> validateChapter(
            @PathVariable @NotBlank(message = "章节ID不能为空") String chapterId) {
        boolean exists = chapterService.existsByChapterId(chapterId);
        return ResponseEntity.ok(ApiResponse.success(exists));
    }
    
    /**
     * 验证章节是否属于指定课程
     */
    @GetMapping("/{chapterId}/course/{courseId}/validate")
    public ResponseEntity<ApiResponse<Boolean>> validateChapterBelongsToCourse(
            @PathVariable @NotBlank(message = "章节ID不能为空") String chapterId,
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId) {
        boolean belongs = chapterService.validateChapterBelongsToCourse(chapterId, courseId);
        return ResponseEntity.ok(ApiResponse.success(belongs));
    }
    
    /**
     * 获取学生已学习的章节
     * 兼容单体系统API: GET /api/chapters/student/{userId}/course/{courseId}/learned
     */
    @GetMapping("/student/{userId}/course/{courseId}/learned")
    public ResponseEntity<ApiResponse<List<Chapter>>> getLearnedChaptersByStudent(
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId,
            @PathVariable @NotBlank(message = "课程ID不能为空") String courseId) {
        log.info("获取学生已学习章节: userId={}, courseId={}", userId, courseId);
        List<Chapter> chapters = chapterService.getLearnedChaptersByStudent(userId, courseId);
        return ResponseEntity.ok(ApiResponse.success(chapters));
    }
    
    /**
     * 标记章节为已完成状态
     * 兼容单体系统API: POST /api/chapters/student/{userId}/{chapterId}/finish
     */
    @PostMapping("/student/{userId}/{chapterId}/finish")
    public ResponseEntity<ApiResponse<Void>> markChapterAsFinished(
            @PathVariable @NotBlank(message = "用户ID不能为空") String userId,
            @PathVariable @NotBlank(message = "章节ID不能为空") String chapterId) {
        log.info("标记章节完成: userId={}, chapterId={}", userId, chapterId);
        chapterService.markChapterAsFinished(userId, chapterId);
        return ResponseEntity.ok(ApiResponse.success("章节标记完成成功"));
    }
}